<!--
  密钥管理组件
  创建时间：2025-09-12
  作者：开发团队
  目的：管理系统的加密密钥
-->

<template>
  <div class="key-management">
    <el-card class="management-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h2>密钥管理</h2>
          <div class="header-actions">
            <el-button
              type="primary"
              :loading="loading"
              @click="generateKey"
            >
              <el-icon><Plus /></el-icon>
              生成新密钥
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 密钥列表 -->
      <div class="keys-section">
        <el-table
          v-loading="loading"
          :data="keys"
          stripe
          class="keys-table"
        >
          <el-table-column prop="id" label="ID" width="80" />
          
          <el-table-column prop="content" label="密钥内容" width="200">
            <template #default="{ row }">
              <el-text truncated>{{ row.content }}</el-text>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getKeyStatusType(row.status)">
                {{ getKeyStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="expired_at" label="过期时间" width="180">
            <template #default="{ row }">
              {{ row.expired_at ? formatDate(row.expired_at) : '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'active'"
                type="warning"
                size="small"
                @click="archiveKey(row.id)"
              >
                归档
              </el-button>
              <el-button
                v-else-if="row.status === 'archived'"
                type="success"
                size="small"
                @click="activateKey(row.id)"
              >
                激活
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteKey(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          
          <template #empty>
            <el-empty description="暂无密钥数据" />
          </template>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalKeys"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { showError, showSuccess } from '@/utils/message'
import { formatDate } from '@/utils/date'
import type { Key } from '@/types/admin'
import { adminApi } from '@/api/admin'

// 响应式状态
const loading = ref(false)
const keys = ref<Key[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalKeys = ref(0)

/**
 * 获取密钥列表
 */
const loadKeys = async (): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API获取密钥列表
    const response = await adminApi.getKeys({
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value
    })
    keys.value = response.data || []
    // 注意：当前API不返回总数，需要后端支持分页
    totalKeys.value = keys.value.length
  } catch (error) {
    console.error('加载密钥列表失败:', error)
    showError('加载密钥列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 生成新密钥
 */
const generateKey = async (): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API生成新密钥
    await adminApi.createKey({
      created_by: 1 // 当前用户ID，实际应用中应从认证信息中获取
    })
    showSuccess('密钥生成成功')
    await loadKeys()
  } catch (error) {
    console.error('生成密钥失败:', error)
    showError('生成密钥失败')
  } finally {
    loading.value = false
  }
}

/**
 * 归档密钥
 * :param keyId: 密钥ID
 */
const archiveKey = async (keyId: number): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API归档密钥
    await adminApi.archiveKey(keyId)
    showSuccess(`密钥归档成功`)
    await loadKeys()
  } catch (error) {
    console.error('归档密钥失败:', error)
    showError('归档密钥失败')
  } finally {
    loading.value = false
  }
}

/**
 * 激活密钥
 * :param keyId: 密钥ID
 */
const activateKey = async (keyId: number): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API激活密钥
    await adminApi.activateKey(keyId)
    showSuccess(`密钥激活成功`)
    await loadKeys()
  } catch (error) {
    console.error('激活密钥失败:', error)
    showError('激活密钥失败')
  } finally {
    loading.value = false
  }
}

/**
 * 删除密钥
 * :param keyId: 密钥ID
 */
const deleteKey = async (keyId: number): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API删除密钥
    await adminApi.deleteKey(keyId)
    showSuccess(`密钥删除成功`)
    await loadKeys()
  } catch (error) {
    console.error('删除密钥失败:', error)
    showError('删除密钥失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取密钥状态类型
 * :param status: 密钥状态
 * :return: Element Plus标签类型
 */
const getKeyStatusType = (status: string): 'success' | 'warning' | 'info' => {
  switch (status) {
    case 'active':
      return 'success'
    case 'archived':
      return 'warning'
    default:
      return 'info'
  }
}

/**
 * 获取密钥状态文本
 * :param status: 密钥状态
 * :return: 状态文本
 */
const getKeyStatusText = (status: string): string => {
  switch (status) {
    case 'active':
      return '活跃'
    case 'archived':
      return '已归档'
    case 'expired':
      return '已过期'
    default:
      return status
  }
}

/**
 * 处理分页大小变化
 */
const handleSizeChange = (): void => {
  currentPage.value = 1
  loadKeys()
}

/**
 * 处理当前页变化
 */
const handleCurrentChange = (): void => {
  loadKeys()
}

/**
 * 组件挂载时初始化数据
 */
onMounted(() => {
  loadKeys()
})
</script>

<style scoped>
.key-management {
  height: 100%;
}

.management-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.keys-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.keys-table {
  flex: 1;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>